package com.atzly.community.service.impl;

import com.atzly.community.constant.ActiveConstant;
import com.atzly.community.constant.CommentConstant;
import com.atzly.community.entity.LoginTicket;
import com.atzly.community.entity.User;
import com.atzly.community.mapper.UserMapper;
import com.atzly.community.service.UserService;
import com.atzly.community.utils.CommunityUtils;
import com.atzly.community.utils.MailClient;
import com.atzly.community.utils.RedisKeyUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author zlysimida
 * @date 2021/8/24 - 12:58
 */
@Service
public class UserServiceImpl implements UserService, CommentConstant {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private MailClient mailClient;

//    @Autowired
//    private LoginTicketService loginTicketService;
    @Autowired
    private RedisTemplate redisTemplate;

    // 上下文服务路径
    @Value("${server.servlet.context-path}")
    private String contextPath;

    // 社区url
    @Value("${community.path.domin}")
    private String domain;

    /**
     * 重构
     * 将用户缓存到redis中
     * @param id
     * @return
     */
    @Override
    public User selectById(int id) {
        // return userMapper.selectById(id);
        User user = getCache(id);
        if(user == null){
            user = initCache(id);
        }
        return user;
    }

    @Override
    public User selectByName(String username) {
        return userMapper.selectByName(username);
    }

    @Override
    public User selectByEmail(String email) {
        return userMapper.selectByEmail(email);
    }

    @Override
    public int insertUser(User user) {
        return userMapper.insertUser(user);
    }

    /**
     * 重构
     * @param id
     * @param status
     * @return
     */
    @Override
    public int updateStatus(int id, int status) {
        int rows = userMapper.updateStatus(id, status);
        clearCache(id);
        return rows;
    }

    @Override
    public int updateHeader(int id, String headerUrl) {
        int rows = userMapper.updateHeader(id, headerUrl);
        clearCache(id);
        return rows;
    }

    @Override
    public int updatePassword(int id, String password) {
        int rows = userMapper.updatePassword(id, password);
        clearCache(id);
        return rows;
    }

    @Override
    public Map<String, Object> registerService(User user) {
        Map<String,Object> map = new HashMap<>();
        // 空值处理
        if(user == null){
            throw new IllegalArgumentException("用户不能为空!");
        }
        if(StringUtils.isBlank(user.getUsername())){
            map.put("usernameMsg","账号不能为空!");
            return map;
        }
        if(StringUtils.isBlank(user.getPassword())){
            map.put("passwordMsg","密码不能为空!");
            return map;
        }
        if(StringUtils.isBlank(user.getEmail())){
            map.put("emailMsg","邮箱不能为空!");
            return map;
        }

        // 数据库处理
        User u = userMapper.selectByName(user.getUsername());
        if(u != null){
            map.put("usernameMsg","该账号已经存在!");
            return map;
        }

        u = userMapper.selectByEmail(user.getEmail());
        if(u != null){
            map.put("emailMsg","该邮箱已被注册!");
            return map;
        }

        // 注册处理
        user.setSalt(CommunityUtils.randomString().substring(0,5));
        user.setPassword(CommunityUtils.md5(user.getPassword() + user.getSalt()));
        user.setStatus(0);
        user.setType(0);
        user.setActivationCode(CommunityUtils.randomString());
        user.setHeaderUrl(String.format("http://images.nowcoder.com/head/%dt.png",new Random().nextInt(100)));
        user.setCreateTime(new Date());
        userMapper.insertUser(user);

        // 激活邮箱
        Context context = new Context();
        context.setVariable("eamil", user.getEmail());
        // 拼接Url:http://localhost:8080/community/activation/101/code
        String url = domain + contextPath + "/activation/" + user.getId() + "/" + user.getActivationCode();
        context.setVariable("url",url);
        String content = templateEngine.process("/mail/activation",context);
        mailClient.sendMail(user.getEmail(),"激活账号",content);
        return map;
    }

    @Override
    public int activation(int userId,String code) {
        User user = userMapper.selectById(userId);
        if(user.getStatus() == 1){
            return ActiveConstant.ACTIVE_CONSTAN_REPEAT.getCode();
        }else if(user.getActivationCode().equals(code)){
            userMapper.updateStatus(userId,1);
            clearCache(userId);
            return ActiveConstant.ACTIVE_CONSTAN_SUCCESS.getCode();
        }else {
            return ActiveConstant.ACTIVE_CONSTAN_DEFAULT.getCode();
        }
    }


    @Override
    public Map<String, Object> login(String username, String password, int expiredSeconds) {
        Map<String, Object> map = new HashMap<>();
        // 空值判断
        if(StringUtils.isBlank(username)){
            map.put("usernameMsg","账号不能为空!");
            return map;
        }

        if(StringUtils.isBlank(password)){
            map.put("passwordMsg","密码不能为空!");
            return map;
        }

        // 验证账号
        User user = userMapper.selectByName(username);
        if(user == null){
            map.put("usernameMsg","该账号不存在");
            return map;
        }

        // 验证状态
        if(user.getStatus() == 0){
            map.put("usernameMsg", "该账号未激活!");
            return map;
        }

        // 验证密码
        String s = CommunityUtils.md5(password + user.getSalt());
        if(!user.getPassword().equals(s)){
            map.put("passwordMsg","密码不正确!");
            return map;
        }

        // 生成登录凭证凭证
        LoginTicket loginTicket = new LoginTicket();
        loginTicket.setStatus(0);
        loginTicket.setUserId(user.getId());
        loginTicket.setTicket(CommunityUtils.randomString());
        loginTicket.setExpired(new Date(System.currentTimeMillis() + expiredSeconds * 1000L));
        // loginTicketService.insertTicket(loginTicket);
        // 使用redis重构
        String redisKey = RedisKeyUtils.getLoginTicket(loginTicket.getTicket());
        redisTemplate.opsForValue().set(redisKey,loginTicket);


        map.put("ticket",loginTicket.getTicket());
        return map;
    }

    @Override
    public void logout(String ticket) {
        //loginTicketService.updateTicketStatus(ticket,1);
        // 将redis中的ticket修改状态为1
        String redisKey = RedisKeyUtils.getLoginTicket(ticket);
        LoginTicket loginTicket = (LoginTicket) redisTemplate.opsForValue().get(redisKey);
        loginTicket.setStatus(1);
        redisTemplate.opsForValue().set(redisKey,loginTicket);
    }

    @Override
    public LoginTicket selectTicketById(String ticket) {
        // 查询reids中的ticket
        String redisKey = RedisKeyUtils.getLoginTicket(ticket);
        return (LoginTicket) redisTemplate.opsForValue().get(redisKey);
    }


    // 重构用户到缓存中
    // 从缓存中获取值
    private User getCache(int userId){
        String userKey = RedisKeyUtils.getUserKey(userId);
        return  (User) redisTemplate.opsForValue().get(userKey);
    }

    // 取不到时初始化缓存
    private User initCache(int userId){
        User user = userMapper.selectById(userId);
        String userKey = RedisKeyUtils.getUserKey(userId);
        redisTemplate.opsForValue().set(userKey,user,3600, TimeUnit.SECONDS);
        return user;
    }

    // 清除缓存
    private void clearCache(int userId){
        String userKey = RedisKeyUtils.getUserKey(userId);
        redisTemplate.delete(userKey);
    }

    // 返回用户权限
    // 返回的就是一个权限集合
    public Collection<? extends GrantedAuthority> getAuthorities(int userId) {
        User user = userMapper.selectById(userId);

        List<GrantedAuthority> list = new ArrayList<>();
        // 这里仅仅添加一个权限
        list.add((GrantedAuthority) () -> {
            switch (user.getType()){
                case 1:
                    return AUTHORITY_ADMIN;
                case 2:
                    return AUTHORITY_MODERATOR;
                default:
                    return AUTHORITY_USER;
            }
        });
        return list;
    }
}
